package com.atguigu.day08;

import com.atguigu.bean.Acc;
import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.AggregatingState;
import org.apache.flink.api.common.state.AggregatingStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

public class Flink07_State_KeyedState_AggState {

    public static void main(String[] args) throws Exception {

        //1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.读取数据
        DataStreamSource<String> socketTextStream = env.socketTextStream("hadoop102", 9999);

        //3.将每行数据转换为JavaBean
        SingleOutputStreamOperator<WaterSensor> waterSensorDS = socketTextStream.map(line -> {
            String[] fields = line.split(",");
            return new WaterSensor(fields[0],
                    Long.parseLong(fields[1]),
                    Double.parseDouble(fields[2]));

        });

        //4.按照传感器Id分组
        KeyedStream<WaterSensor, String> keyedStream = waterSensorDS.keyBy(WaterSensor::getId);

        //5.使用状态编程实现计算每个传感器的平均水位
        SingleOutputStreamOperator<Tuple2<String, Double>> result = keyedStream.process(new KeyedProcessFunction<String, WaterSensor, Tuple2<String, Double>>() {

            //定义状态
            private AggregatingState<Double, Double> aggregatingState;

            @Override
            public void open(Configuration parameters) throws Exception {

                aggregatingState = getRuntimeContext().getAggregatingState(new AggregatingStateDescriptor<Double, Acc, Double>(
                        "agg-state",
                        new AggregateFunction<Double, Acc, Double>() {
                            @Override
                            public Acc createAccumulator() {
                                return new Acc(0.0D, 0);
                            }

                            @Override
                            public Acc add(Double value, Acc accumulator) {

                                accumulator.setVcSum(accumulator.getVcSum() + value);
                                accumulator.setCount(accumulator.getCount() + 1);

                                return accumulator;
                            }

                            @Override
                            public Double getResult(Acc accumulator) {
                                return accumulator.getVcSum() / accumulator.getCount();
                            }

                            @Override
                            public Acc merge(Acc a, Acc b) {

                                a.setVcSum(a.getVcSum() + b.getVcSum());
                                a.setCount(a.getCount() + b.getCount());

                                return a;
                            }
                        }, Acc.class
                ));
            }

            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<Tuple2<String, Double>> out) throws Exception {

                //将当前数据存入状态
                aggregatingState.add(value.getVc());

                //输出数据
                out.collect(new Tuple2<>(value.getId(), aggregatingState.get()));
            }
        });

        //6.打印
        result.print();

        //7.启动
        env.execute();

    }

}
